package com.crm.redis.mapper;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ZsetRMapper {


	public static Set<String> getRedisStringZSet(StringRedisTemplate redisTemplate, String key,double max,double min) {
		if (key == null) {
            return null;
        }
		try {
			return redisTemplate.opsForZSet().rangeByScore(key, max, min);
		} catch (Exception e) {
			log.error("R_ValueRedisMapper getRedisString ERROR:", e);
			log.error("Data:" + key);
			throw e;
		}
	}

	public static boolean addRedisString(StringRedisTemplate redisTemplate, String key, String value,double score) {
		if (key == null || value == null) {
            return false;
        }
		try {
			redisTemplate.opsForZSet().add(key, value, score);
			return true;
		} catch (Exception e) {
			log.error("R_ValueRedisMapper getRedisString ERROR:", e);
			log.error("Data:" + key);
			throw e;
		}
	}
	
	public static boolean removeRedisString(StringRedisTemplate redisTemplate, String key, String value) {
		if (key == null || value == null) {
            return false;
        }
		try {
			redisTemplate.opsForZSet().remove(key, value);
			return true;
		} catch (Exception e) {
			log.error("R_ValueRedisMapper getRedisString ERROR:", e);
			log.error("Data:" + key);
			throw e;
		}
	}

	public static boolean setRedisTimeout(StringRedisTemplate redisTemplate, String key, long timeout, TimeUnit timeunit) {
		if (key == null) {
            return false;
        }
		try {
			if (timeout == 0) {
                redisTemplate.delete(key);
            } else {
                redisTemplate.expire(key, timeout, timeunit);
            }
			return true;
		} catch (Exception e) {
			log.error("R_ValueRedisMapper getRedisString ERROR:", e);
			log.error("Data:" + key);
			throw e;
		}
	}

	public static boolean delRedis(StringRedisTemplate redisTemplate, String string) {
		if (StringUtils.isBlank(string)) {
			return false;
		} else {
			try {
				redisTemplate.delete(string);
				return true;
			} catch (Exception e) {
				log.error("R_ValueRedisMapper getRedisString ERROR:", e);
				log.error("Data:" + string);
				throw e;
			}
		}
	}

	public static boolean delRedisList(StringRedisTemplate redisTemplate, List<String> strings) {
		if (strings.size() > 0) {
			return false;
		}
		try {
			redisTemplate.delete(strings);
			return true;
		} catch (Exception e) {
			log.error("R_ValueRedisMapper getRedisString ERROR:", e);
			log.error("Data:" + strings);
			throw e;
		}
	}

}
